<template>
  <view class="cart-container">
    <view class="content">
      <!-- 判断购物车是否有商品，有商品则显示商品列表 -->
      <view v-if="shopGroups.length > 0">
        <!-- 超市分组 -->
        <view v-for="(shopGroup, shopIndex) in shopGroups" :key="shopIndex" class="shop-group">
          <!-- 超市头部 -->
          <view class="shop-header">
            <checkbox :checked="shopGroup.allChecked" @click="handleShopAllCheck(shopGroup)">
              {{ shopGroup.shopname }}
            </checkbox>
            <view @click="clea(shopGroup)" id="clear">清除所有</view>
          </view>
          <!-- 商品列表 -->
          <view v-for="(product, productIndex) in shopGroup.products" :key="productIndex" class="product-card">
            <checkbox :checked="product.checked" @click="handleItemCheck(product, shopGroup)" />
            <image class="product-img" :src="Config.API_HOST + product.imgUrl" mode="aspectFill" />

            <view class="product-info">
              <text class="product-title">{{ product.name }}</text>
              <text class="sales">已售{{ product.sales }}</text>

              <view class="price-container">
                <text class="current-price">¥{{ product.price.toFixed(2) }}元</text>
                <text class="old-price" v-if="product.oldPrice">¥{{ product.oldPrice.toFixed(2) }}元</text>
              </view>

              <view class="quantity-control">
                <button class="quantity-btn" @click.stop="decreaseQuantity(product)">-</button>
                <text class="quantity">{{ product.quantity }}</text>
                <button class="quantity-btn" @click.stop="increaseQuantity(product)">+</button>
              </view>
            </view>
          </view>
          <!-- 底部汇总 -->
          <view class="cart-footer">
            <text>总计: ¥ <text style="color: red;">{{ calculateGroupTotal.get(shopGroup.shopname) }}</text>元</text>
            <button class="goCheckout" @click="goCheckout(shopGroup.shopname, shopGroup)">去结算</button>
          </view>
        </view>
      </view>
      <!-- 购物车没有商品时显示的部分 -->
      <view style="text-align: center;" v-else>
        <text >购物车空空如也~</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import { onShow } from "@dcloudio/uni-app";
import Config from '@/config.js';

// 响应式数据
const shopGroups = ref([]);
const num = ref(0);

// 获取购物车数据
const fetchCartData = async () => {
  try {
    const res = await uni.request({
      url: Config.API_HOST + "/carts" + "/?token=" + uni.getStorageSync("token"),
      method: 'GET'
    });
    if (!Array.isArray(res.data)) {
      uni.showToast({
        title: '数据格式错误',
        icon: 'none'
      });
      return;
    }
    // 按超市分组
    const groupMap = {};
    for (let i = 0; i < res.data.length; i++) {
      const item = res.data[i];
      const shopName = item.shopname;
      if (!groupMap[shopName]) {
        groupMap[shopName] = {
          shopname: shopName,
          products: [],
          allChecked: false
        };
      }
      // 初始化商品数据
      groupMap[shopName].products.push({
        ...item,
        checked: false,
        quantity: item.quantity || 1
      });
    }
    shopGroups.value = Object.values(groupMap);

  } catch (error) {
    uni.showToast({
      title: '获取购物车数据失败',
      icon: 'none'
    });
  }
};

// 计算单个超市的总价
const calculateGroupTotal = computed(() => {
  const map = new Map();
  shopGroups.value.forEach(element => {
    let total = 0;
    element.products.forEach((item) => {
      if (item.checked) {
        total += Number(item.price) * Number(item.quantity);
      }
    });
    map.set(element.shopname, total);
  });
  return map;
});

// 超市全选/取消全选
const handleShopAllCheck = (group) => {
  group.allChecked = !group.allChecked;
  group.products.forEach(product => {
    product.checked = group.allChecked;
  });
  if (group.allChecked) {
    num.value = group.products.length;
  } else {
    num.value = 0;
  }
};

// 单个商品选中状态变化
const handleItemCheck = (product, group) => {
  product.checked = !product.checked;
  if (product.checked) {
    num.value++;
    if (num.value == group.products.length) {
      group.allChecked = group.products.every(p => p.checked);
    }
  } else {
    num.value--;
    if (num.value != group.products.length) {
      group.allChecked = false;
    }
  }
};

// 增加商品数量
const increaseQuantity = (product) => {
  product.quantity++;
  const datas = {
    id: product.id,
    _id: product._id,
    name: product.name,
    imgUrl: product.imgUrl,
    sales: product.sales,
    price: product.price,
    oldPrice: product.oldPrice,
    seckill: product.seckill,
    shopId: product.shopId,
    quantity: product.quantity,
    shopname: product.shopname
  };
  uni.request({
    url: `${Config.API_HOST}/carts/${product.id}`,
    method: "PUT",
    header: {
      'Content-Type': 'application/json'
    },
    data: JSON.stringify(datas),
    success: (res) => {
      console.log(res.data);
    }
  });
};

// 减少商品数量
const decreaseQuantity = (product) => {
  product.quantity--;

  if (product.quantity == 0) {
    uni.request({
      url: `${Config.API_HOST}/carts/${product.id}`,
      method: "DELETE",
      success: (res) => {
        fetchCartData();
      },
      fail: (err) => {
        console.error('删除商品失败:', err);
      }
    });
  } else {
    const datas = {
      id: product.id,
      _id: product._id,
      name: product.name,
      imgUrl: product.imgUrl,
      sales: product.sales,
      price: product.price,
      oldPrice: product.oldPrice,
      seckill: product.seckill,
      shopId: product.shopId,
      quantity: product.quantity,
      shopname: product.shopname
    };
    uni.request({
      url: `${Config.API_HOST}/carts/${product.id}`,
      method: "PUT",
      header: {
        'Content-Type': 'application/json'
      },
      data: JSON.stringify(datas),
      success: (res) => {
        console.log(res.data);
      }
    });
  }
};

// 删除商品
const clea = (group) => {
  group.products.forEach((product) => {
    uni.request({
      url: `${Config.API_HOST}/carts/${product.id}`,
      method: "DELETE",
      success: (res) => {
        fetchCartData();
      },
      fail: (err) => {
        console.error('删除商品失败:', err);
      }
    });
  });
};

// 生命周期钩子
onShow(() => {
  const token = uni.getStorageSync('token');
  if (token) {
    fetchCartData();
  } else {	
	uni.navigateTo({
		url:"/pages/login/index"
	})
    return;
  }
  })
// 去结算
const goCheckout = (shopname, shopGroup) => {
  // 获取选中的商品
  const selectedProducts = shopGroup.products.filter(product => product.checked);
  
  // 检查是否有选中的商品
  if (selectedProducts.length === 0) {
    uni.showToast({
      title: '请先选择商品',
      icon: 'none'
    });
    return;
  }

  // 将选中的商品存储到本地存储
  uni.setStorageSync('selectedProducts', JSON.stringify(selectedProducts));

  // 跳转到结算页面
  uni.navigateTo({
    url: `/pages/cartcheckout/index?shopname=${shopname}`,
  });
};
</script>

<style scoped>
.goCheckout {
  background-color: rgb(233,59,59);
  color:white;
  line-height: 40px;
  margin-right: 0px;
  
}

.cart-footer {
  height: 40px;
  display: flex;
}

.cart-footer>text {
  line-height: 40px;
}

.shop-header #clear {
  margin-right: 0px;
  background-color: white;
}

.cart-container {
  padding: 20rpx;
  background-color: #f7f7f7;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.all-check {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: white;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
}

.all-check checkbox {
  margin-right: 10rpx;
}

.shop-group {
  background: white;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

.shop-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.shop-header checkbox {
  margin-right: 10rpx;
}

.shop-header text {
  margin-right: 0px;
}

.product-card {
  display: flex;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  align-items: center;
}

.product-card checkbox {
  margin-right: 20rpx;
}

.product-img {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.product-title {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
  margin-bottom: 10rpx;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.sales {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 15rpx;
}

.price-container {
  display: flex;
  align-items: baseline;
  margin-bottom: 15rpx;
}

.current-price {
  color: #e93b3b;
  font-size: 32rpx;
  font-weight: bold;
  margin-right: 15rpx;
}

.old-price {
  color: #999;
  font-size: 24rpx;
  text-decoration: line-through;
}

.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 50rpx;
  height: 50rpx;
  line-height: 50rpx;
  text-align: center;
  border: 1rpx solid #ddd;
  background: #f7f7f7;
  font-size: 28rpx;
  padding: 0;
  margin: 0;
}

.quantity {
  margin: 0 20rpx;
  font-size: 28rpx;
}

.shop-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #fafafa;
}

.total-text {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.checkout-all-btn {
  background: #e93b3b;
  color: white;
  border-radius: 40rpx;
  padding: 0 50rpx;
  height: 70rpx;
  line-height: 70rpx;
  font-size: 28rpx;
}
</style>